package com.lyw.GeoLocationClient.ui;

import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.RouteNode;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.lyw.GeoLocationClient.R;
import timber.log.Timber;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RouteLinePlayer {

    // 通过设置间隔时间和距离可以控制速度和图标移动的距离
    private static final int TIME_INTERVAL = 80;
    private static final double DISTANCE = 0.0001;
    private RouteLinePlayerCallback callBack;

    private BaiduMap mMap;
    private Polyline mRoute;
    private MarkerOptions mMoveMarkerOption;
    private Marker mMoveMarker;

    private volatile boolean play;
    private volatile boolean stop;
    private ArrayList<LatLng> mList;

    private volatile boolean isPlaying;

    public RouteLinePlayer(BaiduMap baiduMap, RouteLinePlayerCallback cb) {
        this.mMap = baiduMap;
        this.callBack = cb;
    }

    public void setCallBack(RouteLinePlayerCallback callBack) {
        this.callBack = callBack;
    }

    private void setData(Polyline line) {
        mRoute = line;
        setData(line.getPoints());
    }

    private void setData(List<LatLng> list) {
        stop();
        mList = new ArrayList<LatLng>();
        mList.addAll(list);

//        Collections.reverse(mList);
        initMarker(mList.get(0));
    }

    private void initMarker(LatLng poi) {
        if (mMoveMarker != null) {
            mMoveMarker.remove();
        }

        mMoveMarkerOption = new MarkerOptions();
        mMoveMarkerOption.flat(true);
        mMoveMarkerOption.anchor(0.5f, 0.5f);
        mMoveMarkerOption.icon(BitmapDescriptorFactory
                .fromResource(R.drawable.marker));
        mMoveMarkerOption.position(poi);

//        mMap.clear();
        mMoveMarker = (Marker) mMap.addOverlay(mMoveMarkerOption);

        LatLng ll = new LatLng(poi.latitude,
                poi.longitude);
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 17.0f);
        mMap.animateMapStatus(u);
    }

    public void play(List<LatLng> list) {
        Timber.d("play " + list.size());
        setData(list);

        play();
        moveLooper();
    }

    public void play() {
        stop = false;
        play = true;
        isPlaying = true;
    }


    public void pause() {
        play = false;
        if (callBack != null) {
            callBack.onRoutePause();
        }
        isPlaying = false;
        Timber.d("set isplaying" + isPlaying);

    }

    public void stop() {
        stop = true;
        play = false;
        isPlaying = false;

        if (mMoveMarker != null) {
            mMoveMarker.remove();
        }
        Timber.d("set isplaying" + isPlaying);

    }

    public boolean isPlaying() {
        return isPlaying;
    }

    public interface RouteLinePlayerCallback {
        void onRouteStart();

        void onRoutePause();

        void onRouteStop();
        void onRouteProgress(int index, int total);
    }

//    private double getAngle(int startIndex) {
//        if ((startIndex + 1) >= points.size()) {
//            throw new RuntimeException("index out of bonds");
//        }
//        LatLng startPoint = points.get(startIndex);
//        LatLng endPoint = points.get(startIndex + 1);
//        return getAngle(startPoint, endPoint);
//    }

    /**
     * 根据两点算取图标转的角度
     */
    private double getAngle(LatLng fromPoint, LatLng toPoint) {
        double slope = getSlope(fromPoint, toPoint);
        if (slope == Double.MAX_VALUE) {
            if (toPoint.latitude > fromPoint.latitude) {
                return 0;
            } else {
                return 180;
            }
        }
        float deltAngle = 0;
        if ((toPoint.latitude - fromPoint.latitude) * slope < 0) {
            deltAngle = 180;
        }
        double radio = Math.atan(slope);
        double angle = 180 * (radio / Math.PI) + deltAngle - 90;
        return angle;
    }

    /**
     * 根据点和斜率算取截距
     */
    private double getInterception(double slope, LatLng point) {

        double interception = point.latitude - slope * point.longitude;
        return interception;
    }

    /**
     * 算取斜率
     */
//    private double getSlope(int startIndex) {
//        if ((startIndex + 1) >= points.size()) {
//            throw new RuntimeException("index out of bonds");
//        }
//        LatLng startPoint = points.get(startIndex);
//        LatLng endPoint = points.get(startIndex + 1);
//        return getSlope(startPoint, endPoint);
//    }

    /**
     * 算斜率
     */
    private double getXMoveDistance(double slope) {
        if (slope == Double.MAX_VALUE) {
            return DISTANCE;
        }
        return Math.abs((DISTANCE * slope) / Math.sqrt(1 + slope * slope));
    }

    private double getSlope(LatLng fromPoint, LatLng toPoint) {
        if (toPoint.longitude == fromPoint.longitude) {
            return Double.MAX_VALUE;
        }
        double slope = ((toPoint.latitude - fromPoint.latitude) / (toPoint.longitude - fromPoint.longitude));
        return slope;

    }

    /**
     * 循环进行移动逻辑
     */
    public void moveLooper() {
        if (callBack != null) {
            callBack.onRouteStart();
        }


        final List<LatLng> points = mList;

        new Thread() {

            public void run() {
                int size = points.size();
                Timber.d("size  " + size);
                for (int i = 0; i < size - 1; i++) {
                    while (!play) {
                        if (stop) {
                            break;
                        }
                        try {
                            Thread.sleep(TIME_INTERVAL);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    if (stop) {
                        break;
                    }

                    LatLng startPoint = points.get(i);
                    LatLng endPoint = points.get(i + 1);
                    mMoveMarker
                            .setPosition(startPoint);

                    mMoveMarker.setRotate((float) getAngle(startPoint,
                            endPoint));

                    double slope = getSlope(startPoint, endPoint);
                    //是不是正向的标示（向上设为正向）
                    boolean isReverse = (startPoint.latitude > endPoint.latitude);

                    double intercept = getInterception(slope, startPoint);

                    double xMoveDistance = isReverse ? getXMoveDistance(slope)
                            : -1 * getXMoveDistance(slope);


                    for (double j = startPoint.latitude;
                         !((j > endPoint.latitude) ^ isReverse);

                         j = j
                                 - xMoveDistance) {
                        if (startPoint.latitude == endPoint.latitude) {
                            break;
                        }
                        if (stop) {
                            break;
                        }

                        LatLng latLng = null;
                        if (slope != Double.MAX_VALUE) {
                            latLng = new LatLng(j, (j - intercept) / slope);
                        } else {
                            latLng = new LatLng(j, startPoint.longitude);
                        }
                        mMoveMarker.setPosition(latLng);
                        while (!play) {
                            if (stop) {
                                break;
                            }
                            try {
                                Thread.sleep(TIME_INTERVAL);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }

                        try {
                            Thread.sleep(TIME_INTERVAL);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    if (callBack != null) {
                        callBack.onRouteProgress(i, size);
                    }
                }

                if (callBack != null) {
                    callBack.onRouteStop();
                    stop = true;
                    play = false;
                    isPlaying = false;

                    if (mMoveMarker != null) {
                        mMoveMarker.remove();
                    }
                }
            }
        }.start();
    }
}
